<template>
  <div class="doAnswer">
    <div class="questionDetailHeader">
      <img src="../../assets/image/goBack.png" @click="goBack"/>
      <p>我来回答</p>
    </div>
    <div class="questionBox">
      <p class="title">{{qmess}}</p>
      <p class="name">{{quser|fiterPhone}}<span class="data">{{qdate|filterTime5}}</span></p>
    </div>
    <div class="answerBox">


      <textarea style="resize: none" v-model="text" placeholder="等待回答。。"></textarea>
      <span class="count">{{textLength}}/100</span>
    </div>
    <div class="photos" v-show="showList==0">
      <div class="imgBox">
        <img  src="../../assets/image/question/photo.png" alt=""  @click="showAction">
        <label for="upfile" class="op"></label>
      </div>
      <p>上传照片</p>
    </div>
    <div class="picList" v-if="showList.length>0">
      <ul>
        <li  v-for="(img,index) in showList" @click="showImg(index)"><img :src="img" alt=""></li>

        <li class="addIcon" @click="showAction" v-if="this.showList.length<4"><img  src="../../assets/image/question/add.png" alt="" ><label for="upfile" class="op"></label></li>
        <li class="picCount">{{imgList.length}}/4</li>
      </ul>
    </div>
    <div  :class="{active:textLength>0,btn:true}" @click="submit">确认</div>
    <!--底部弹窗-->
    <actionsheet v-model="sheetVisible" :menus="{menu1:'上传图像'}" @on-click-menu-menu1="addPic"  show-cancel></actionsheet>
    <!--查看头像-->
    <popup v-model="popupVisible" height="100%" style="background: #ffffff">
      <div class="questionDetailHeader">
        <img src="../../assets/image/goBack.png" @click="goClose"/>
        <p>{{imgIndex+1}}/4</p>
        <span class="close" @click="deleteImg">删除</span>
      </div>
      <div class="popupImg" >
        <img  :src="showImg1" style="width:100%"/>
      </div>
    </popup>
    <!--<div class="bigImg">-->
      <!--<img  src="../../assets/image/question/good1.jpg" />-->
    <!--</div>-->
    <!--<Previewer></Previewer>-->

    <input type="file" @change="onFileChange" style="display:none" id="upfile" >
   <!--  <toast v-model="showdisc" type="text" text="买过该商品的用户才可以评论" position='top'></toast> -->
    <confirm v-model="confirmVisible" title="提示" @on-confirm="goLogin">
      <p style="text-align:center;">您当前尚未登录，现在前往登录？</p>
    </confirm>

      <alert v-model="showdisc" title="提示" ></alert>

  </div>
</template>
<script>
/*我来回答*/
import {XHeader,Actionsheet,Popup,Alert,Previewer,Toast,Confirm} from 'vux';
import { setCookie, getCookie } from '../../util/commonUtils';
export default {
  name:"doAnswer",
  // 数据
  data(){

    return{
    	userId:'',
      text:'', //输入的文字
      textLength:0,//文字长度
      hasPic:false,//是否上传了图片
      sheetVisible:false,//底部弹窗是否可见
      allData:'',//所有个人信息

      popupVisible:false,//
      imgList:[],//上传图片列表;
      showList:[],//显示的列表
      quser:sessionStorage.getItem('quser'),
      qdate:Number(sessionStorage.getItem('qdate')),
      qmess:sessionStorage.getItem('qmess'),
      showdisc:false,
      showImg1:'',
      imgIndex:'',
      confirmVisible:false,
      images:[],
    }
  },
  // 计算属性
  watch:{
    //监听text的长度
    text:function(newText,oldText){

      this.textLength=newText.length;
      if(newText.length>100){
        this.text=oldText
      }
    }
  },
  computed:{

  },
  // 创建（实例创建完成）
  created(){
    this.userId=getCookie('loginkey');

    console.log(Number(this.qdate))
  },
  // el被创建，并挂载到实例上
  mounted(){

  },
  // 方法（实例中的方法）-----------
  methods:{
     goLogin() {
            this.$router.push('/login');
    },
    goBack(){
      this.$router.go(-1)
    },
    showImg(index){
      this.popupVisible=true;
      this.imgIndex=index;
      this.showImg1=this.showList[index]

    },
    showAction(){
     // this.sheetVisible=true;
    },
    deleteImg(){

        this.imgList.splice(this.imgIndex,1);
        this.showList.splice(this.imgIndex,1);

      this.popupVisible = false;
    },
    goClose(){
      this.popupVisible = false;
    },
    addPic(){

       this.sheetVisible = false;
    },
    submit(){
      if(!this.text){
        this.$vux.alert.show({title:'提示',content:'请输入回答内容!'});return;
      }
       this.$vux.loading.show({
          text: ''
        });
      if(!this.userId) {
        this.confirmVisible = true;
        return;
      }
      let obj={};
      obj.QUESTION_ID=this.$route.params.id;
      obj.USER_ID=this.userId;
      obj.MESSAGE=this.text;
      obj.PHOTO_ARRAY=JSON.stringify(this.imgList);

      this.$fetchPost("serviceDetailQA/setServiceDetailAnswer",obj).then(res=>{

         this.$vux.loading.hide();
        console.log(res)
        if(res.STATUS_CODE==1){
          this.$router.go(-1)
        }
      },err=>{
        console.log(err)
      })
    },
    autoClick(){
      document.getElementById("upfile").click();//写两次才能自动触发点击事件
      this.sheetVisible = false;
    },
//    onFileChange($event) {
//      console.log($event)
//      var files = $event.target.files || $event.dataTransfer.files;
//      //console.log(files)
//      if (!files.length)return;
//      this.createImage(files);
//    },
//    createImage(file) {
//      if(typeof FileReader==='undefined'){
//        alert('您的浏览器不支持图片上传，请升级您的浏览器');
//        return false;
//      }
//      if(this.images.length>0){
//        this.images=[];
//      }
//      var image = new Image();
//      var vm = this;
//      var leng=file.length;
//      for(var i=0;i<leng;i++){
//        var reader = new FileReader();
//        reader.readAsDataURL(file[i]);
//        reader.onload =function(e){
//          vm.images.push(e.target.result)
//          console.log(vm.images)
//        };
//      }
//    },
//
      //压缩图片
    convertImgToBase64(url, callback, outputFormat){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var img = new Image;
        img.crossOrigin = 'Anonymous';
        img.onload = function(){
          var width = img.width;
          var height = img.height;
          // 按比例压缩4倍
          var rate = (width<height ? width/height : height/width)/4;
          canvas.width = width*rate;
          canvas.height = height*rate;
          ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);
          var dataURL = canvas.toDataURL(outputFormat || 'image/png');
          callback.call(this, dataURL);
          canvas = null;
        };
        img.src = url;
    },
        //获取图片url路径
    getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) {  // basic
          url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) {       // mozilla(firefox)
          url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // web_kit or chrome
          url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    },
    onFileChange($event){
      if(this.showList.length>=4){
        return;
      }
        //图片预览fileReader
      let fr = new FileReader();
      let that = this;
      let imgUrl=this.getObjectURL($event.target.files[0])
      this.convertImgToBase64(imgUrl,function(base64Img){
            //console.log(base64Img)
            that.imgList.push(base64Img.split(",")[1])
           that.showList.push(base64Img)

      })

      fr.readAsDataURL($event.target.files[0]);

      let Img =this.getObjectURL($event.target.files[0])
     // let that = this;
      let sImg = document.getElementById('showImg');
      fr.onload = function(evt){
        let obj = {};
        obj.USER_ID = that.userId;
        obj.IMAGE = evt.target.result.split(",")[1];


      // that.imgList.push(obj.IMAGE)
      // that.showList.push('data:image/jpeg;base64,'+obj.IMAGE)
      //  console.log(this.showList)
      //   that.$fetchPost('/CUserWeb/UploadImageBase64.action',obj).then(res=>{
      //     //console.dir(res);
      //     if(res.STATUS_CODE == 1){
      //      //that.showList.push(res.AVATAR);
      //      }
      // },err=>console.log(err));
      }

    },
  },
  // 子组件
  components:{
    XHeader,
    Actionsheet,
    Popup,
    Alert,
    Toast,
    Confirm
  }
}
</script>
<!--当前页面的样式 -->
<style lang="less" scoped>

  .vue-popup-dialog{
    position:absolute;
    top:1.2rem;
    left:0;
    bottom:0;
    width:100%;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
  }
.doAnswer{
    width: 7.5rem;
    height: 100%;
    overflow: hidden;
    background: #fff;
  .questionDetailHeader{
    position: relative;
    height:0.8rem;
    line-height:0.8rem;
    font-size:0.33rem;
    color:#222222;
    img{
      position: absolute;
      left: 0.22rem;
      bottom: 0.25rem;
      height: 0.38rem;
    }
    .close{
      position: absolute;
      top:0;
      font-size: 0.28rem;
      color:#666666;
      right:0.3rem;
      line-height: 0.8rem;
    }
  }
  .questionBox{
    height: 1.5rem;
    width: 100%;
    padding-top:0.33rem;
    padding-left:0.31rem;
    text-align:left;
    .title{
      font-size: 0.29rem;
      color: #222222;
      margin-bottom: 0.3rem;
    }
    .name{
      font-size:0.19rem;
      color: #888888;
      .data{
        float: right;
        margin-right: 0.3rem;
      }
    }
  }
  .answerBox{
    position:relative;
    textarea{
      display: block;
      margin-left: 0.2rem;
      height: 2.7rem;
      width: 7.1rem;
      border:none;
      background:#f6f6f6 ;
      line-height: 0.4rem;
      font-size:0.29rem;
      color: #999999;
      padding: 0.3rem;
    }
    .count{
      position: absolute;
      right:0.4rem;
      bottom: 0.2rem;
      font-size: 0.27rem;
      color:#999999;
    }
  }
  .photos{
    position: relative;
    img{
      position: absolute;
      left: 0.2rem;
      top:0.2rem;
      height: 1.1rem;
      width: 1.1rem;
    }
    .op{
      position: absolute;
      left: 0.2rem;
      top:0.2rem;
      height: 1.1rem;
      width: 1.1rem;
      z-index: 5;

    }
    p{
      padding-left: 1.5rem;
      font-size: 0.25rem;
      color:#999999;
      line-height: 1.5rem;
      text-align: left;
    }
  }
  .picList{
    ul{
      overflow: hidden;
      width:6rem;
      li{
        float: left;
        position: relative;
        border: 1px solid #dddddd;
        border-radius:0.06rem;
        margin: 0.2rem 0 0 0.2rem;
        height: 1.1rem;
        width: 1.1rem;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .addIcon{
        .op{
          position: absolute;
          top:0.3rem;
          left:0.3rem;
          width: 0.5rem;
          height: 0.5rem;
          vertical-align: middle;
          z-index: 9
        }
        img{
          position: absolute;
          top:0.3rem;
          left:0.3rem;
          width: 0.5rem;
          height: 0.5rem;
          vertical-align: middle;
        }
      }
      .picCount{
        border-color: #ffffff;
        font-size:0.25rem;
        line-height: 1.1rem;
        color: #999999;
      }
    }

  }
  .btn{
    position: absolute;
    bottom:0.3rem;
    left: 50%;
    margin-left: -1.4rem;
    width: 2.8rem;
    height: 0.7rem;
    border-radius: 0.35rem;
    background: #f5f5f5;
    font-size:0.26rem!important;
    color: #999999;
    display: flex;
    display:-webkit-flex;
    justify-content:center;
    align-items:center;
    text-align: center;
  }
  .active{
    background: #F22E2E;
    color: #ffffff;
  }
}
.weui-toast{
  width: 4rem!important;
}
.questionDetailHeader:after{
  content: '';
  position: absolute;
  bottom: 0 ;
  left:0 ;
  width: 100%;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  height: 1px;
  background: #dddddd;
}
</style>
